import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { getCartListApi, insertCartApi, deleteCartApi } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()
    const isLogin = computed(() => {
      return userStore.userInfo.token
    })
    const cartList = ref([])

    const getCartList = async () => {
      const res = await getCartListApi()
      cartList.value = res.result
    }
    const addCart = async (goods) => {
      const { skuId, count } = goods
      if (isLogin.value) {
        // 登录加入购物车逻辑
        await insertCartApi({ skuId, count })
        getCartList()
      } else {
        // 未登录加入购物车逻辑
        const item = cartList.value.find((item) => item.skuId === goods.skuId)
        if (!item) {
          cartList.value.push(goods)
        } else {
          item.count += goods.count
        }
      }
    }
    const delCart = async (skuId) => {
      if (isLogin.value) {
        await deleteCartApi([skuId])
        getCartList()
      } else {
        cartList.value = cartList.value.filter((item) => item.skuId !== skuId)
      }
    }

    const clearCart = () => {
      cartList.value = []
    }

    const totalCount = computed(() => {
      return cartList.value.reduce((pre, item) => {
        return pre + item.count
      }, 0)
    })

    const totalPrice = computed(() => {
      return cartList.value.reduce((pre, item) => {
        return pre + item.count * item.price
      }, 0)
    })

    const updateSelected = (skuId, selected) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      if (item) {
        item.selected = selected
      }
    }
    const isAllSelected = computed(() => {
      return cartList.value.every((item) => item.selected)
    })

    const updateAllSelected = (selected) => {
      cartList.value.forEach((item) => {
        item.selected = selected
      })
    }
    const checkedCount = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((pre, item) => {
          return pre + item.count
        }, 0)
    })
    const checkedPrice = computed(() => {
      return cartList.value
        .filter((item) => item.selected)
        .reduce((pre, item) => {
          return pre + item.count * item.price
        }, 0)
    })
    return {
      cartList,
      totalCount,
      totalPrice,
      isAllSelected,
      checkedCount,
      checkedPrice,
      addCart,
      delCart,
      updateSelected,
      updateAllSelected,
      clearCart,
      getCartList,
    }
  },
  {
    persist: true,
  },
)
